﻿/****************************************************************************

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

-- Copyright 2010 Elizabeth Elizondo
-- Deploy Workflow Manager
****************************************************************************/


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.Workflow;

/*
*	Title: Deploy Workflow Manager
*   Author: Elizabeth Elizondo
*   Date: 5/3/2010
*   Implemenation: 5/10/2010
*   Change Set 1: 5/11/2010
*   Change Set 2: 5/24/2010
*/

namespace workFlowMgr
{
    [Guid("a3acf037-7e9d-40ea-9453-afb806ab1649")]
    public class workFlowMgr : System.Web.UI.WebControls.WebParts.WebPart
    {
        public workFlowMgr()
        {
        }

        #region Variables
        private Button startWork;
        private Label showInfo;
        private Label showMessg;
        private Label showReqs;
        private SPSite getSite;
        private SPWeb getWeb;
        private SPList getList;
        private SPListItemCollection collListItems;
        private LiteralControl lc;
        private LiteralControl lc2;
        private LiteralControl lc3;
        private DropDownList ddlWorkflows;
        private string currentValue;
        private List<string> reqNums;        
        #endregion

        #region OnInit
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            startWork = new Button();
            showInfo = new Label();
            showMessg = new Label();
            showReqs = new Label();
            lc = new LiteralControl();
            lc2 = new LiteralControl();
            lc3 = new LiteralControl();
            ddlWorkflows = new DropDownList();
            reqNums = new List<string>();            
            EnsureChildControls();
        }
        #endregion

        #region CreateChildControls
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            showInfo.ID = "lblShowInfo";
            showInfo.Text = "Workflows associated with the " + ListName + " list:</br>";
            this.Controls.Add(showInfo);

            //Create drop down list box
            ddlWorkflows.ID = "WrkFlowName";
            ddlWorkflows.AutoPostBack = true;
            ddlWorkflows.EnableViewState = true;
            ddlWorkflows.SelectedIndexChanged += new EventHandler(ddlWorkflows_SelectedIndexChanged);
            this.Controls.Add(ddlWorkflows);

            //Create space between controls
            lc.Text = "</br></br>";
            this.Controls.Add(lc);

            //Create Button to Start the Workflow
            startWork.ID = "btnStart";
            startWork.Width = 150;
            startWork.Text = "Start Workflow";
            startWork.Click += new EventHandler(startWork_Click);
            startWork.Visible = false;
            this.Controls.Add(startWork);

            //Create space between controls.
            lc2.Text = "</br>";
            this.Controls.Add(lc2);

            //Create Label to display Successfull message
            showMessg.ID = "lblMessg";
            this.Controls.Add(showMessg);

            //Create space between controls.
            lc3.Text = "</br></br>The following item(s) were processed...</br>";
            lc3.Visible = false;
            this.Controls.Add(lc3);

            //Create Label to display Requests that were Archived
            showReqs.ID = "lblReqs";
            this.Controls.Add(showReqs);
        }
        #endregion

        #region WebPartProperties
        #region SiteUrl
        /// <summary>
        /// Site Url.
        /// </summary>
        [WebBrowsable(true),
        Category("Workflow Manager Properties"),
        DefaultValue(defaultSiteUrl),
        Personalizable(PersonalizationScope.Shared),
        WebDisplayName("Site Url"),
        WebDescription("Use this field to set the Site URL. Default is http://sharepointservername")]
        public string SiteUrl
        {
            get
            {
                string sUrl;
                if ((SiteSrc != null) && (SiteSrc.Length > 0))
                    sUrl = SiteSrc;
                else
                    sUrl = defaultSiteUrl;

                return sUrl;
            }
            set { SiteSrc = value; }
        }
        private const string defaultSiteUrl = "/";
        private string SiteSrc = String.Empty;
        #endregion

        #region ListName
        /// <summary>
        /// List Name.
        /// </summary>
        [WebBrowsable(true),
        Category("Workflow Manager Properties"),
        DefaultValue(defaultListName),
        Personalizable(PersonalizationScope.Shared),
        WebDisplayName("List Name"),
        WebDescription("Use this field to set the Name of the List.")]
        public string ListName
        {
            get
            {
                string lName;
                if ((ListSrc != null) && (ListSrc.Length > 0))
                    lName = ListSrc;
                else
                    lName = defaultListName;

                return lName;
            }
            set { ListSrc = value; }
        }
        private const string defaultListName = "Documents";
        private string ListSrc = String.Empty;
        #endregion

        #region FieldName
        /// <summary>
        /// Field Name.
        /// </summary>
        [WebBrowsable(true),
        Category("Workflow Manager Properties"),
        DefaultValue(defaultFieldName),
        Personalizable(PersonalizationScope.Shared),
        WebDisplayName("Internal Field Name"),
        WebDescription("Set the Internal Field Name in the List to display.")]
        public string FieldName
        {
            get
            {
                string fName;
                if ((FieldSrc != null) && (FieldSrc.Length > 0))
                    fName = FieldSrc;
                else
                    fName = defaultFieldName;

                return fName;
            }
            set { FieldSrc = value; }
        }
        private const string defaultFieldName = "Title";
        private string FieldSrc = String.Empty;
        #endregion

        #region FieldTitle
        /// <summary>
        /// Field Title.
        /// </summary>
        [WebBrowsable(true),
        Category("Workflow Manager Properties"),
        DefaultValue(defaultFieldTitle),
        Personalizable(PersonalizationScope.Shared),
        WebDisplayName("Field Title"),
        WebDescription("Set the Display Field Title in the List to display.")]
        public string FieldTitle
        {
            get
            {
                string FTName;
                if ((FieldTitleSrc != null) && (FieldTitleSrc.Length > 0))
                    FTName = FieldTitleSrc;
                else
                    FTName = defaultFieldTitle;

                return FTName;
            }
            set { FieldTitleSrc = value; }
        }
        private const string defaultFieldTitle = "Title";
        private string FieldTitleSrc = String.Empty;
        #endregion
        #endregion

        #region OnLoad
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!Page.IsPostBack)
            {
                getWorkflows();
            }
        }
        #endregion

        #region getWorkflows
        private void getWorkflows()
        {
            using (getSite = SPContext.Current.Site)
            {
                using (getWeb = SPContext.Current.Site.OpenWeb(SiteUrl))
                {
                    try
                    {
                        getList = getWeb.Lists[ListName];
                        collListItems = getList.Items;
                        SPWorkflowManager spMgr = getSite.WorkflowManager;
                        SPWorkflowAssociationCollection assocColl = getList.WorkflowAssociations;

                        foreach (SPWorkflowAssociation assoc in assocColl)
                        {
                            ddlWorkflows.Items.Add(new ListItem(assoc.Name, assoc.Id.ToString()));
                            ddlWorkflows.DataTextField = assoc.Name;
                            ddlWorkflows.DataValueField = assoc.Id.ToString();
                        }
                        ddlWorkflows.Items.Insert(0, "Select Workflow");
                        ddlWorkflows.DataBind();
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
            }
        }
        #endregion

        #region ddlWorkflows_SelectedIndexChanged
        private void ddlWorkflows_SelectedIndexChanged(object sender, EventArgs e)
        {
            startWork.Visible = true;
            showMessg.Text = "";
            lc3.Visible = false;
            showReqs.Text = "";
        }
        #endregion

        #region StartWorkFlowClick
        private void startWork_Click(object sender, EventArgs e)
        {
            showMessg.Text = "";
            lc3.Visible = false;
            showReqs.Text = "";
            string getCurrentSite = SPContext.Current.Site.Url.ToString();

            using (getSite = new SPSite(getCurrentSite))
            {
                using (getWeb = getSite.OpenWeb(SiteUrl))
                {
                    try
                    {
                        getList = getWeb.Lists[ListName];
                        collListItems = getList.Items;
                        //Grab current selected Workflow value in the drop-down list
                        currentValue = this.ddlWorkflows.SelectedValue.ToString();

                        int i = 0;

                        foreach (SPListItem itm in collListItems)
                        {
                            //get the workflow associated with this list and kick if off manually 
                            SPWorkflowAssociation wrkFl = getList.WorkflowAssociations[new Guid(currentValue)];
                            getSite.WorkflowManager.StartWorkflow(itm, wrkFl, wrkFl.AssociationData, true);

                            //Keep count of how many items are being processed
                            i = i + 1;

                            //Store each list item being archived                                    
                            reqNums.Add(itm[FieldName].ToString());
                        }

                        showMessg.Text = i + " Item(s) successfully processed.";

                        //If any line items were processed display info
                        if (i != 0)
                        {
                            lc3.Visible = true;
                            foreach (string reqItm in reqNums)
                            {
                                showReqs.Text += FieldTitle + reqItm + "</br>";
                            }
                        }
                        ddlWorkflows.SelectedIndex = 0;
                        startWork.Visible = false;
                    }
                    catch (Exception w)
                    {
                        throw w;
                    }
                }
            }
        }

        #endregion

        #region Render
        protected override void Render(HtmlTextWriter output)
        {
            EnsureChildControls();

            try
            {
                base.Render(output);
            }
            catch (Exception e)
            {
                output.Write(e.ToString());
            }
        }
        #endregion

        #region SubstringCalcDate
        //Remove description displayed before the date from the calculated column field.  Ex: datetime;#2010-01-01 00:00:00
        public string Substring(string text)
        {
            int startIndex = 9;
            startIndex = text.IndexOf("#");
            return text.Substring((startIndex + 1)).Trim();
        }
        #endregion
    }
}


